package com.cl.auth.password;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.cl.dao.SearchDao;
import com.cl.entity.UUser;

public class UsernamePasswordRealm extends JdbcRealm {

    private static final Logger logger = LoggerFactory.getLogger(UsernamePasswordRealm.class);

    @Autowired
    private SearchDao<?> searchDao;
    
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.debug("UsernamePasswordRealm doGetAuthenticationInfo");
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        if (username == null) {
            throw new AccountException("username cannot be null");
        }
        AuthenticationInfo info;
        UUser user = searchDao.getUserByUid(username);
        if (user == null || user.getPwd() == null) {
            throw new UnknownAccountException("username  [" + username + "] not exists");
        }
        info = new SimpleAuthenticationInfo(user, user.getPwd(), getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	return null;
    }

}